/**
 * @Author: likang xie
 * @Date: 2019-11-13 14:15:57
 * @Usage: 上传图片/文件
 */

import config from "@/config";
import store from "@/store";
import toast from "@/utils/toast";

import { getFileName } from "@/apis/task";

/**
 * @param path 文件链接
 */
export default path => {
  return new Promise((resolve, reject) => {
    let url = "/doc/fileUpload";

    if (process.env.NODE_ENV == "development") {
      config.remote = config.remote;//"http://120.27.199.64:8518/api";
    } else {
      url = url.replace("/doc", "");
    }
    
    url = url.replace("/doc", "");
    // #ifdef H5
    // config.remote = "http://120.27.199.64:8518/api";
    // #endif

    // #ifndef H5
    url = url.replace("/doc", "");
    // #endif         
    console.log("url", url);
// alert(1)
// async listDelivery() {
//   let params = {
//     id: this.info.id,
//   };

//   let { code, data } = 
//   if (code == 200) this.deliverys = data || [];
// },

console.log("path",path)
var fileName = uni.getStorageSync("pathName")
var first = fileName.lastIndexOf(".");//取到文件名开始到最后一个点的长度
var namelength = fileName.length;//取到文件名长度
var filesuffix = fileName.substring(first + 1, namelength );//截取获得后缀名
// alert(filesuffix );

var ossUrl = 'https://zhihuawang.oss-cn-beijing.aliyuncs.com'
    uni.uploadFile({
      url: ossUrl,//输入你的bucketname.endpoint
      filePath: path,
      fileType: 'image',
      name: 'file',
      formData: {
        name: '22222',
        key: uni.getStorageSync("dir")+new Date().getTime()+'.'+filesuffix,
        policy: uni.getStorageSync("policy"), // 输入你获取的的policy
        OSSAccessKeyId: uni.getStorageSync("accessid"), // 输入你的AccessKeyId
        success_action_status: '200', // 让服务端返回200,不然，默认会返回204
        signature: uni.getStorageSync("signature"), // 输入你获取的的signature
        callback: uni.getStorageSync("callback"), 
      },
      success: res => {
        if(res.statusCode == '200'){
         
          // let params = {
          //   filename:uni.getStorageSync("dir")+new Date().getTime()+'.'+filesuffix,
          //   filesize:uni.getStorageSync("pathSize"),
          //   def_filename:uni.getStorageSync("pathName")
          // };
    
          // let { code, data } =  getFileName(params);
          // console.log('code',resolve(code));
          // if (code == 1000) {
          //   toast("上传成功");
          //   // var dataid = data.attach_id
          //   // uni.setStorageSync("attach_id",dataid)
          // }
        }else{
          console.log(res);
        }
      }
    });

    // uni
    //   .uploadFile({
    //     url: config.remote + url,
    //     url: 'https://zhihuawang.oss-cn-beijing.aliyuncs.com',
        
    //     filePath: path,
    //     name: "file",
    //     formData: {
    //       token: uni.getStorageSync("userInfo").token || ""
    //     }
    //   })
    //   .then(chunk => {
    //     let [err, res] = chunk;

    //     if (res) {
    //       let { code, data, message } = JSON.parse(res.data);

    //       // 未登录/重新登录/Token过期
    //       if (code == 1011) {
    //         toast("未登录或已过期");
    //         store.dispatch("SET_USER_INFO", "");
    //         return uni.navigateTo({
    //           url: "/user/login"
    //         });
    //       }

    //       if (code != 1000) return toast(message || "上传失败，请重试");
    //       resolve(data);
    //     } else {
    //       console.error(err);
    //       reject(err);
    //     }
    //   });
  });
};
export let urlTobase64 = (url)=>{
  uni.request({
    url: url,
    method: 'GET',
    responseType: 'arraybuffer',
    success: res => {
        let base64 = wx.arrayBufferToBase64(res.data); //把arraybuffer转成base64
        base64 = 'data:image/jpeg;base64,' + base64; //不加上这串字符，在页面无法显示
        console.log(base64);
        return base64;
    }
});
}
/**
 * @method: app 本地文件上传
 * @param path 文件路径
 */
export const appUpload = path => {
	return new Promise((resolve, reject) => {
		let url = "/fileUpload";
		let userInfo = uni.getStorageSync("userInfo") || {};
		
		var uploadTask = plus.uploader.createUpload(config.remote + url, { method: "POST" }, (response, status) => {
			console.log(status);
			if (status === 200) {
				let { code, data, message } = JSON.parse(response.responseText);
				console.log(response);
				if (code === 1000) {
					resolve(data);
				} else reject("上传失败");
				
				// 未登录/重新登录/Token过期
				if (code == 1011) {
				  toast("未登录或已过期");
				  store.dispatch("SET_USER_INFO", "");
				  return uni.navigateTo({
				    url: "/user/login"
				  });
				}
			} else {
				reject("上传失败");
			}
		});
		uploadTask.addFile(path, { key: "file" });
		uploadTask.addData("token", userInfo.token);
		uploadTask.start();
	});
}
